package net.lcqf.websocket.send;

import io.netty.channel.Channel;
import net.lcqf.websocket.server.MsgInfoPojo;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2021-2025 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2025/4/16 11:43
 * // +----------------------------------------------------------------------
 */

@Component
public class MessageFactory {

    private static final Map<Integer, MessageBaseService> MESSAGE = new HashMap<>();

    public static void register(Integer type, MessageBaseService messageBaseService) {
        Assert.notNull(type, "type must not be null");
        Assert.notNull(messageBaseService, "messageBaseService must not be null");
        Assert.isNull(MESSAGE.putIfAbsent(type, messageBaseService),"type already exists");
    }

    public Object sendMessage(Channel channel, MsgInfoPojo.MsgInfo msgInfo) {
        MessageBaseService tClass = MESSAGE.get(msgInfo.getRequestType());
        return Optional.ofNullable(tClass.sendMessage(channel, msgInfo.getData())).orElse(defaultMessage());
    }

    private Object defaultMessage() { return null; }
}
